package org.jeecg.modules.platform.organization.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.depart.entity.SysDepart;
import org.jeecg.modules.platform.config.service.ICyPlatformConfigOrgStateAndRoleTypeService;
import org.jeecg.modules.platform.config.service.ICyPlatformRouteConfigService;
import org.jeecg.modules.platform.entity.CyPlatformConfigOrgStateAndRoleType;
import org.jeecg.modules.platform.entity.CyPlatformOrganizationAndMember;
import org.jeecg.modules.platform.entity.CyPlatformOrganizationInfo;
import org.jeecg.modules.platform.entity.CyPlatformRouteConfig;
import org.jeecg.modules.platform.member.service.ICyPlatformOrganizationAndMemberService;
import org.jeecg.modules.platform.organization.mapper.CyPlatformOrganizationInfoMapper;
import org.jeecg.modules.platform.organization.service.ICyPlatformOrganizationInfoService;
import org.jeecg.modules.platform.organization.service.ICyPlatformOrganizationPermissionService;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.user.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @Description: 平台组织管理
 * @Author: jeecg-boot
 * @Date: 2024-10-25
 * @Version: V1.0
 */
@Service
public class CyPlatformOrganizationInfoServiceImpl extends ServiceImpl<CyPlatformOrganizationInfoMapper, CyPlatformOrganizationInfo> implements ICyPlatformOrganizationInfoService {

    @Autowired
    ISysDepartService departService;
    @Autowired
    ICyPlatformOrganizationPermissionService organizationPermissionService;

    @Autowired
    ICyPlatformConfigOrgStateAndRoleTypeService roleTypeService;
    @Autowired
    ICyPlatformRouteConfigService routeConfigService;


    @Autowired
    private ICyPlatformOrganizationAndMemberService orgMemberService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public String register(CyPlatformOrganizationInfo orgInfo) {
        SysDepart sysDepart = buildDepart(orgInfo);
        // 利用一级部门作为分类
        sysDepart.setCostCalcSubject(true);
        // 一级部门是顶级组织
        sysDepart.setTopOrg(true);
        // 先保存部门会生成部门ID
        departService.saveDepartData(sysDepart);

        // 初始化组织信息
        orgInfo.setOrganizationCode(sysDepart.getOrgCode());
        orgInfo.setDeptId(sysDepart.getId());
        orgInfo.setDelFlag(CommonConstant.DEL_FLAG_0);

        this.save(orgInfo);
        return sysDepart.getId();
    }

    @Override
    public void updateUserOrganizationId(String organizationInfoId, String deptId) {
        // 绑定用户
        Subject currentUser = SecurityUtils.getSubject();
        LoginUser loginUser = (LoginUser) currentUser.getPrincipal();
        if (StringUtils.isEmpty(loginUser.getOrganizationId())) {
            loginUser.setOrganizationId(organizationInfoId);
            loginUser.setDeptId(deptId);
            // 更新shiro
            currentUser.runAs(new SimplePrincipalCollection(loginUser, "realname"));
            // 删除缓存
            redisUtil.del(CacheConstant.SYS_USERS_CACHE + "::" + loginUser.getUsername());
            // 更新用户信息
            userService.updateById(new SysUser().setOrganizationId(organizationInfoId).setDepartId(deptId).setId(loginUser.getId()));
        }
        orgMemberService.save(new CyPlatformOrganizationAndMember()
                .setOrganizationId(organizationInfoId)
                .setUserId(loginUser.getId())
                .setDefaultBind(true)
        );

    }

    @Override
    public List<String> getPermissionList(String orgId) {
        return Optional.ofNullable(getById(orgId))
                .map(CyPlatformOrganizationInfo::getState)
                .map(state -> roleTypeService.getOne(new LambdaQueryWrapper<CyPlatformConfigOrgStateAndRoleType>().eq(CyPlatformConfigOrgStateAndRoleType::getState, state)))
                .map(CyPlatformConfigOrgStateAndRoleType::getOrgType)
                .map(orgType -> routeConfigService.getOne(new QueryWrapper<>(new CyPlatformRouteConfig().setType(orgType))))
                .map(CyPlatformRouteConfig::getComment)
                .map(comment -> comment.split(","))
                .map(Arrays::asList)
                .orElse(Collections.emptyList());
    }

    private SysDepart buildDepart(CyPlatformOrganizationInfo organizationInfo) {
        SysDepart dept = new SysDepart();
        dept.setParentId("");
        dept.setOrganizationId(organizationInfo.getId());
        dept.setDepartName(organizationInfo.getName());
        dept.setAddress(organizationInfo.getAddress());
        return dept;
    }

}
